import * as shopService from '../../services/shop/shop';
import * as systemService from '../../services/system';

export default {
  namespace: 'customer',
  state:{
    pageRows:{},
    customerTypes:[],
  },
  reducers: {
    updatePageRows(state, {payload}) {
      const newstate = state;
      newstate.pageRows = payload;
      return newstate;
    },
    updateRow(state, {payload}) {
      const newstate = state;
      let index=null;
      const datas=newstate.pageRows.data;
      for(var i=0;i<datas.length;i++){
        if(datas[i].id==payload.id){
          index=i;
          break;
        }
      }
      if(index!=null){
        newstate.pageRows.data[index]=payload;
      }
      return newstate;
    },
    updateCustomerTypes(state, {payload}) {
      const newstate = state;
      newstate.customerTypes = payload;
      return newstate;
    },
  },
  effects: {
    *e_getPageCustomers({payload}, {call, put}) {
      const {data} = yield call(shopService.getPageCustomers,payload);
      yield put({type: 'updatePageRows', payload: data});
    },
    *e_delete({payload}, {call, put}) {
      yield call(shopService.deleteCustomers,payload);
      yield put({type: 'e_getPageCustomers',payload:payload.params});
    },
    *e_add({payload}, {call, put}) {
      yield call(shopService.addOrUpdateCustomer,payload);
      yield put({type: 'e_getPageCustomers',payload:{
        pageNumber:1,
        pageSize:10
      }});
    },
    *e_update({payload}, {call, put}) {
      const {data} = yield call(shopService.addOrUpdateCustomer,payload);
      yield put({type: 'updateRow',payload:data});
    },
    *e_customerTypes({payload}, {call, put}) {
      const {data} = yield call(systemService.getCustomerTypes);
      yield put({type: 'updateCustomerTypes',payload:data});
    },
  },

}
